import { notification } from 'antd';
import { history, request as umiRequest } from 'umi';

// 定义API响应类型
export interface ApiResponse<T = any> {
  total: number;
  code: string;
  msg: string | null;
  data: T;
  map: Record<string, any>;
}

// 定义API基础URL
export const BASE_URL = '/api';

/**
 * 自定义请求函数
 * @param url 请求路径
 * @param options 请求选项
 * @returns Promise<ApiResponse<T>>
 */
async function request<T = any>(
  url: string,
  options?: Record<string, any>,
): Promise<ApiResponse<T>> {
  // 添加基础URL
  const fullUrl = url.startsWith('http') ? url : `${BASE_URL}${url}`;

  // 默认配置
  const defaultOptions: {
    timeout: number;
    headers?: Record<string, string>;
    [key: string]: any;
  } = {
    timeout: 10000,
    headers: {},
    ...options,
  };

  // 添加token到请求头
  const token = localStorage.getItem('token');
  if (token && !url.includes('/login/loginIn')) {
    defaultOptions.headers = {
      ...defaultOptions.headers,
      token: `${token}`,
    };
  }

  try {
    // 发送请求并直接获取数据
    const data = await umiRequest(fullUrl, defaultOptions);

    // 处理业务逻辑错误
    if (data && data.code !== '0000') {
      // 可以在这里统一处理错误，比如token过期等
      if (data.code === '1001') {
        // 假设1001是token过期的错误码
        // 处理token过期
        localStorage.removeItem('token');
        history.push('/login');
      }
    }

    return data as ApiResponse<T>;
  } catch (error: any) {
    // 处理网络错误
    const { response } = error;
    if (response && response.status) {
      notification.error({
        message: `请求错误 ${response.status}`,
        description: '请求发生错误，请稍后再试',
      });
    } else {
      notification.error({
        message: '网络异常',
        description: '您的网络发生异常，无法连接服务器',
      });
    }
    throw error;
  }
}

export default request;
